const express = require("express");
const { getUnix } = require("../../model/tools");
const ArticleCateModel = require("../../model/ArticleCateModel");
const ArticleModel = require("../../model/ArticleModel")
const mongoose = require('../../model/core')

var router = express.Router();
router.get("/", async (req, res) => {
    // 进行表关联，找_id等于pid的数据
    let result = await ArticleCateModel.aggregate([
        {
            $lookup: {
                from: "article_cate",
                localField: "_id",
                foreignField: "pid",
                as: "items"
            }
        },
        {
            $match: {
                pid: "0"
            }
        }
    ])

    res.render("admin/articleCate/index.html", {
        list: result
    })
})


router.get("/add", async (req, res) => {

    let topCateList = await ArticleCateModel.find({ "pid": "0" })

    res.render("admin/articleCate/add.html", {
        cateList: topCateList
    })

})

router.post("/doAdd", async (req, res) => {

    // 如果父分类不是顶级分类的情况
    if (req.body.pid != 0) {
        req.body.pid = mongoose.Types.ObjectId(req.body.pid)
    }

    req.body.add_time = getUnix()
    let result = new ArticleCateModel(req.body)
    await result.save()

    res.redirect(`/${req.app.locals.adminPath}/articleCate`)
})


router.get("/edit", async (req, res) => {
    let id = req.query.id
    let result = await ArticleCateModel.find({ "_id": id })

    // 获取顶级分类列表
    let topCateList = await ArticleCateModel.find({ "pid": "0" })
    res.render("admin/articleCate/edit.html", {
        list: result[0],
        cateList: topCateList
    })
})

router.post("/doEdit", async (req, res) => {
    console.log(req.body.pid);
    try {
        // 如果父分类不是顶级分类的情况，转换objectId
        if (req.body.pid != 0) {
            req.body.pid = mongoose.Types.ObjectId(req.body.pid)
        }
        await ArticleCateModel.updateOne({ "_id": req.body.id }, req.body)
        res.render("admin/public/success.html", {
            "redirectUrl": `/${req.app.locals.adminPath}/articleCate`,
            "message": "修改数据成功"
        })
    } catch (error) {
        res.render("admin/public/error.html", {
            "redirectUrl": `/${req.app.locals.adminPath}/articleCate/edit?id=${req.body.id}`,
            "message": "修改数据失败"
        })
    }
})

router.get("/delete", async (req, res) => {
    let id = req.query.id

    // 有子分类的情况下不允许删除
    // 注意：查找pid时需要将id转换为ObjectID
    let childResult = await ArticleCateModel.find({ "pid": mongoose.Types.ObjectId(id) })

    if (childResult.length) {
        res.render('admin/public/error.html', {
            message: '该分类下还有子分类，请先删除子分类后重试',
            redirectUrl: `/${req.app.locals.adminPath}/articleCate`
        })
    } else {
        let subArticleResult = await ArticleModel.find({ "cid": mongoose.Types.ObjectId(id) })
        if (subArticleResult.length) {
            res.render('admin/public/error.html', {
                message: '当前分类下有文章信息没法删除，请删除文章后重试',
                redirectUrl: `/${req.app.locals.adminPath}/articleCate`
            })
        } else {
            await ArticleCateModel.deleteOne({ "_id": id })
            res.render('admin/public/success.html', {
                message: '删除数据成功',
                redirectUrl: `/${req.app.locals.adminPath}/articleCate`
            })
        }
    }


})


module.exports = router